import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Navigator,Image } from '@tarojs/components'
import { CityLocation, OrderItem, DistributorOrder, DistributorOrderStatistics } from '../../utils/server.interface'
import { ComponentClass } from 'react'
import { connect } from 'react-redux'
import { AtSearchBar } from 'taro-ui'
import { http } from '../../utils/http'
import {  RESELLER_ORDER_LIST } from '../../constants/api'
import { user } from '../../utils/user.service'
import {GetRequest,vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './order.scss'

type PageStateProps = {
    location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
    tabIndex: number
    noticeShow: boolean
    loadMoreStatus: "more" | "loading" | "noMore"
    curTabIndex: number
    orderList: DistributorOrder[]
    searchKey: string
    statistics: DistributorOrderStatistics
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface ResellerOrder {
    props: IProps
}

@connect(({location})=>({
    location
}),(dispatch)=>({

}))


class ResellerOrder extends Component {
    tabList = [{ title: '全部', value: -1 }, { title: '已付款', value: 1 }, { title: '已完成', value: 2 }, { title: '已退款', value: 4 }]
    state: PageState = {
        tabIndex: 0,
        noticeShow: true,
        loadMoreStatus: 'loading',
        curTabIndex: 0,
        orderList: [],
        searchKey: '',
        statistics: {
            allPayCount: 0,
            cancelPayCount: 0,
            finishCount: 0,
            offPayCount: 0,
            onPayCount: 0
        }
    }
    page = 1
    sid = 0
    async onReachBottom() {
        if(this.state.loadMoreStatus != 'noMore') {
            this.setState({ loadMoreStatus: 'loading'})
            this.page++
            const orderList = await this.getData(this.page)
            const old = this.state.orderList
            if(orderList){
                this.setState({orderList: [...old, ...orderList]})
            }
        }
    }
    tabClick(index) {
        this.page = 1
        this.setState({ curTabIndex: index, loadMoreStatus: 'loading', orderList: [] }, async () => {
            const orderList = await this.getData(this.page)
            this.setState({orderList})
        })
    }
    noticeClose() {
        this.setState({ noticeShow: false })
    }
    async componentDidShow(){
      vcmonitor(this)
    }
    async UNSAFE_componentWillMount() {
      if(process.env.TARO_ENV==='h5'){
        await h5Wx.getConfig()
      }
        const isLogin = await user.checkLogin()
        if(!isLogin){
            Taro.showToast({
                title: '你还未登录，请登录',
                icon: 'none',
            })
            const timer = setTimeout(() => {
                clearTimeout(timer)
                Taro.switchTab({ url: '/pages/my/index/index' })
            }, 1500)
            return
        }
        const {sid,dateFlag,status} = Taro.getCurrentInstance().router.params
        if(!sid){
            Taro.showToast({
                title: '参数错误',
                icon: 'none',
            })
            const timer = setTimeout(() => {
                clearTimeout(timer)
                Taro.navigateBack()
            }, 1500)
        }
        this.sid = sid
        this.dateFlag = decodeURI(dateFlag)
        let index = 0
        this.tabList.forEach((item, i) => {
            if(item.value == status) index = i
        })
        Taro.showLoading({title: '加载中...'})
        this.tabClick(index)

        setTimeout(() => {
            Taro.hideLoading()
        }, 100)
    }
    async getData(page) {
        const index = this.state.curTabIndex
        const orderList = await http.get<OrderItem[]>(RESELLER_ORDER_LIST, {pageNumber: page,dateFlag:this.dateFlag, orderStatus: this.tabList[index].value, searchKeywords: this.state.searchKey, sid: this.sid})
        if(orderList && orderList.length === 10){
            this.setState({ loadMoreStatus: 'more'})
        } else {
            this.setState({ loadMoreStatus: 'noMore'})
        }
        return orderList || []
    }
    searchChange(value) {
        this.setState({ searchKey: value })
    }
    searchClear() {
        this.setState({ searchKey: '', orderList: [], loadMoreStatus:'loading'}, async () => {
            const orderList = await this.getData(this.page)
            this.setState({orderList})
        })
    }
    search() {
        this.page = 1
        this.setState({ loadMoreStatus: 'loading', orderList: []}, async () => {
            const orderList = await this.getData(this.page)
            if(orderList){
                this.setState({orderList})
            }
        })
    }
    render() {
        const {  loadMoreStatus, orderList, searchKey } = this.state
        return (
            <View className='dist-order-list-root'>
              <GzhAuth />
                <AtSearchBar value={searchKey} onChange={this.searchChange.bind(this)} onClear={this.searchClear.bind(this)} onActionClick={this.search.bind(this)}></AtSearchBar>
              {orderList.map(item => <View key={item.id} className='order-item'>
                <Navigator  url={`/distributor/order/detail?orderId=`+item.id}>
                  <View className='head'>
                    <View className='status'>{item.status_name}</View>
                  </View>
                  <View className='order-info'>
                    <Image className='img' src={item.default_img_url} mode='aspectFill'></Image>
                    <View className='name-box'>
                      <View className='name'>{item.is_meal===1 && <Text style='color:red;'>[套餐]</Text>}{item.product_name}</View>
                      {!!item.memo && <View className='valid-date'>{item.memo}</View>}
                      <View className='date'>{item.add_date}</View>
                    </View>
                    <View className='order-info-right'>
                      <View className='order-info-num'>x{item.buy_amount}</View>
                      {item.pay_source_img && <Image className='order-info-from' src={item.pay_source_img}></Image>}
                    </View>
                  </View>
                  <View className='total'>
                    <View className='title'><Text decode>{item.linkman}</Text></View>
                    <View className='price-box'>
                      <View className='price'>￥<Text>{item.total_fee}</Text></View></View>
                  </View>
                </Navigator>
                <View className='btn-box' style={`${item.isSendSms!==1 && 'border-top:none;'}`}>
                  <View className='btn-item-box' />
                  <View className='btn-item-box'>
                    {item.isSendSms==1 && <View className='btn-item primary'>重发短信</View>}
                  </View>
                </View>
              </View>)}
            </View>
        )
    }
}

export default ResellerOrder as ComponentClass<PageOwnProps, PageState>
